import uuid

from django.urls import reverse
from django.shortcuts import render, redirect
from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt

from web.forms.wiki import addWikiForm
from web import models
from utils.tencent.cos import CosTencent


def wiki(request, project_id):
    """ wiki首页与wiki详细预览页  """
    wiki_id = request.GET.get('wiki')
    # wiki_list = models.Wiki.objects.filter(project_id=project_id).all()
    if not wiki_id or not str(wiki_id).isdecimal():
        # return render(request, 'web/wiki.html', {'wiki_list': wiki_list})
        return render(request, 'web/wiki.html')
    else:
        wiki_object = models.Wiki.objects.filter(id=wiki_id, project_id=project_id).first()
        return render(request, 'web/wiki.html', {'wiki_object': wiki_object})


def wiki_add(request, project_id):
    """ 添加Wiki文档 """
    if request.method == 'GET':
        add_wiki_form = addWikiForm(request)
        return render(request, 'web/wiki_add.html', {'add_wiki_form': add_wiki_form})
    add_wiki_form = addWikiForm(request, data=request.POST)
    if add_wiki_form.is_valid():
        if add_wiki_form.instance.parent:
            add_wiki_form.instance.deepth = add_wiki_form.instance.parent.deepth + 1
        else:
            add_wiki_form.instance.deepth = 1
        add_wiki_form.instance.project_id = project_id
        add_wiki_form.save()
        url = reverse(wiki, kwargs={'project_id': project_id})
        return redirect(url)
    return render(request, 'web/wiki_add.html', {'add_wiki_form': add_wiki_form})


def wiki_delete(request, project_id, wiki_id):
    """ 删除wiki文档 """
    models.Wiki.objects.filter(id=wiki_id, project_id=project_id).delete()
    url = reverse(wiki, kwargs={'project_id': project_id})
    return redirect(url)


def wiki_edit(request, project_id, wiki_id):
    """ 编辑wiki文档 """
    _instance = models.Wiki.objects.filter(id=wiki_id, project_id=project_id).first()
    wiki_object = models.Wiki.objects.filter(project_id=project_id, id=wiki_id).first()
    if not wiki_object:
        url = reverse('wiki', kwargs={'project_id': project_id})
        return redirect(url)
    if request.method == "GET":
        form = addWikiForm(request, instance=_instance)
        return render(request, 'web/wiki_add.html', {'add_wiki_form': form})

    form = addWikiForm(request, data=request.POST, instance=_instance)
    if form.is_valid():
        if form.instance.parent:
            form.instance.depth = form.instance.parent.depth + 1
        else:
            form.instance.depth = 1
        form.save()
        url = reverse('wiki', kwargs={'project_id': project_id})
        preview_url = "{0}?wiki={1}".format(url, wiki_id)
        return redirect(preview_url)

    return render(request, 'web/wiki_add.html', {'add_wiki_form': form})


def wiki_catelog(request, project_id):
    """ 获取wiki的目录结构 """
    wiki_list = models.Wiki.objects.filter(project_id=project_id).order_by('deepth','id').values('id', 'title', 'parent')
    return JsonResponse({'status': True, 'wiki_list': list(wiki_list)})


@csrf_exempt
def wiki_upload(request, project_id):
    """ markdown本地上传文件调用的接口 """
    # Forbidden (CSRF token missing or incorrect.): /manage/5/wiki/upload/ 处理办法：给这个视图函数解除csrf验证
    result = {
        'success': 0,
        'message': None,
        'url': None
    }
    image_object = request.FILES.get('editormd-image-file')
    if not image_object:
        result['message'] = "文件不存在"
        return JsonResponse(result)
    name = image_object.name
    ext = name.split('.')[-1]
    cos = CosTencent()
    bucket = request.login_user.project.bucket_name
    key = f'{request.login_user.user.mobile_phone}-{str(uuid.uuid4())}.{ext}'
    url = cos.upload(bucket_name=bucket,
               key=key,
               image_object = image_object
               )
    result['success'] = 1
    result['url'] = url
    return JsonResponse(result)
